package com.hz.pay.center.utils;

import com.hz.pay.center.resp.WechatRefundResp;
import com.pay.common.utils.PayDigestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;

/**
 * 调用微信支付的接口
 */
@Component
public class WechatUtil {


    @Autowired
    private RestTemplate restTemplate;


    public void  wechatQrCodePay(){

        System.out.println("微信扫码支付");
    }

    /**
     * 微信退款接口
     */
    public WechatRefundResp wechatTradeRefund(String paySerialNo, BigDecimal refundAmt, String refundSerialNo){

        String url = "https://api.mch.weixin.qq.com/secapi/pay/refund";

//        <xml>
//   <appid>wx2421b1c4370ec43b</appid>
//   <mch_id>10000100</mch_id>
//   <nonce_str>6cefdb308e1e2e8aabd48cf79e546a02</nonce_str>
//   <out_refund_no>1415701182</out_refund_no>
//   <out_trade_no>1415757673</out_trade_no>
//   <refund_fee>1</refund_fee>
//   <total_fee>1</total_fee>
//   <transaction_id>4006252001201705123297353072</transaction_id>
//   <sign>FE56DD4AA85C0EECA82C35595A69E153</sign>
//</xml>


        //1.封装微信接口的请求参数格式
        StringBuffer stringBuffer = new StringBuffer();

        stringBuffer.append("<xml>");
        stringBuffer.append("<appid>").append("").append("</appid>");
        //.....

        //...
        stringBuffer.append("<transaction_id>").append("").append("<transaction_id>");
        stringBuffer.append("</xml>");


        //2.按照文档生成签名
        String sign = null;
        try {
            sign = PayDigestUtil.generateSignature(null,"","");
        } catch (Exception e) {
            e.printStackTrace();
        }

        stringBuffer.toString(); //计算出来

        StringBuffer sb = new StringBuffer();


        //3.签名放到请求参数中
        stringBuffer.append("<xml>");
        stringBuffer.append("<appid>").append("").append("</appid>");
        //.....

        //...
        stringBuffer.append("<transaction_id>").append("").append("<transaction_id>");
        stringBuffer.append("<sign>").append(sign).append("<sign>");

        stringBuffer.append("</xml>");

       //5.解析xml对象。 dom  jdom


        WechatRefundResp refundResp = new WechatRefundResp();

        //4.发送请求，获取结果
        String respXml = restTemplate.postForObject(url,sb.toString(),String.class);


        return refundResp;


    }

    /**
     * 退款查询接口
     */
    public void wechatRefundQuery(){

    }
}
